package cm.cool.system.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @author hwh
 *
 */
public class HttpRequestor {
	
	
	private static CloseableHttpClient httpClient = HttpClients.createDefault();

	public static String charSet = "utf-8";

	private HttpRequestor() {
	}

	public static String doGet(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpClient.execute(httpGet);
		try {
			return EntityUtils.toString(response.getEntity());
		} finally {
			response.close();
		}
	}
	public static String doPost(String url, Map<String, Object> parameterMap) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Iterator<String> keys = parameterMap.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			nvps.add(new BasicNameValuePair(key, (String) parameterMap.get(key)));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, charSet));
		CloseableHttpResponse response = httpClient.execute(httpPost);
		try {
			return EntityUtils.toString(response.getEntity(), charSet);
		} finally {
			response.close();
		}
	}
	public static String doPost(String url, String json) throws Exception {
	// 将JSON进行UTF-8编码,以便传输中文
      HttpPost httpPost = new HttpPost(url);
      httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
      StringEntity se = new StringEntity(json,charSet);
      se.setContentType("text/json");
      httpPost.setEntity(se);
      CloseableHttpResponse response = httpClient.execute(httpPost);
      try {
          return EntityUtils.toString(response.getEntity(), charSet);
      } finally {
          response.close();
      }
  }
	/**
     * 发送请求模板
     * @param requestUrl 请求URL
     * @param requestMethod 请求方式 post get
     * @param outputStr 参数
     * @return
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
        JSONObject jsonObject = null;  
        InputStream inputStream = null;  
        InputStreamReader inputStreamReader = null;  
        BufferedReader bufferedReader = null; 
        HttpURLConnection httpUrlConn = null;
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            httpUrlConn = (HttpURLConnection) url.openConnection();  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
            // 将返回的输入流转换成字符串  
            inputStream = httpUrlConn.getInputStream();  
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
           
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {  
            ce.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {
             try {
                 if(bufferedReader != null) bufferedReader.close();  
                 if(inputStreamReader != null) inputStreamReader.close();  
                 if(inputStream != null) inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }  
            if(httpUrlConn != null)httpUrlConn.disconnect();  
        }
        return jsonObject;  
    } 
    public static void main(String[] args) {
		try {
			String s = HttpRequestor.doGet("https://www.bitstamp.net/api/v2/ticker_hour/ethbtc/");
			System.out.println(s);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}